package com.fyqp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fyqp.pojo.ProductType;
import com.fyqp.mapper.ProductTypeMapper;
import com.fyqp.service.IProductTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fyqp.util.BaseResult;
import com.fyqp.util.ParamUtl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author efire
 * @since 2022-02-19
 */
@Service
public class ProductTypeServiceImpl extends ServiceImpl<ProductTypeMapper, ProductType> implements IProductTypeService {
    @Resource
    private ProductTypeMapper productTypeMapper;

    @Override
    public BaseResult oprPro(ProductType productType) {
        String name = StringUtils.trimToEmpty(productType.getName());
        if (StringUtils.isBlank(name)) {
            return BaseResult.error("名称不能为空");
        }
        Long id = productType.getId();
        if (!ParamUtl.isValidId(id)) {
            if (productTypeMapper.isExist(name) != null) {
                return BaseResult.error("已存在该种类，请勿重复添加");
            }
            ProductType po = new ProductType();
            po.setName(name);
            save(po);
        } else {
            ProductType po = getById(id);
            if (po == null) {
                return BaseResult.error("您要操作的种类不存在");
            }
            if (productTypeMapper.isExistWithId(name, id) != null) {
                return BaseResult.error("已存在该种类，请勿重复添加");
            }
            if (!name.equals(po.getName())) {
                po.setName(name);
                updateById(po);
            }
        }
        return BaseResult.success();
    }

    @Override
    public BaseResult listAll() {
        return BaseResult.success(productTypeMapper.selectList(new LambdaQueryWrapper<ProductType>()
                .orderByDesc(ProductType::getId)));
    }

    @Override
    public BaseResult queryWithId(ProductType productType) {
        Long id = productType.getId();
        ProductType po = getById(id);
        if (po == null) {
            return BaseResult.error("您要操作的种类不存在");
        }
        return BaseResult.success(po);
    }
}
